package com.chenfan.filestore.utils;

import java.io.UnsupportedEncodingException;
import java.util.regex.Pattern;


public class Base64Util {

    public static boolean isBase64(String source) {
        String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
        return Pattern.matches(base64Pattern, source);
    }

    public static String encode(String source){
        if (source == null) {
            return null;
        }
        if ("".equals(source)) {
            return "";
        }
        try {
            return java.util.Base64.getEncoder().encodeToString(source.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    public static String decode(String source){
        if (source == null) {
            return null;
        }
        if ("".equals(source)) {
            return "";
        }
        try {
            return new String(java.util.Base64.getDecoder().decode(source.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

//    public static void main(String[] args) {
//        System.out.println(decode(java.util.Base64.getEncoder().encodeToString("审核发票.pdf".getBytes())));;
//        System.out.println(java.util.Base64.getEncoder().encodeToString("审核发票.pdf".getBytes()));
//    }
}
